<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head th:fragment="head(title)">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title th:replace="${title}">前台公共页面</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" th:href="@{/lib/bootstrap-3.4.1/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/css/my.css}">
    <!-- 动画 -->
    <link rel="stylesheet" th:href="@{/css/animate.css}">
    <!-- bootstrap-bootstrapValidator-->
    <link rel="stylesheet" th:href="@{/lib/bootstrapValidator/bootstrapValidator.min.css}">
    <!-- 轻型信息提示框-->
    <link rel="stylesheet" th:href="@{/lib/toastr/toastr.min.css}">
</head>

<body>
<nav th:fragment="menu(n)" class="navbar navbar-default navbar-fixed-top m-padding">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">
                <img alt="Brand" th:src="@{/favicon.ico}" style="width: 24px;">
            </a>
            <p class="navbar-text navbar-default"><a th:href="@{/}" class="navbar-link m-a-none"><strong class="logo">挚夕导航</strong></a>
            </p>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!--        -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li th:classappend="${n == 1} ? 'active'"><a th:href="@{/}"><span
                        class="glyphicon glyphicon-home">&nbsp;</span>首页</a>
                </li>
                <li th:classappend="${n == 2} ? 'active'"><a th:href="@{/tag}"><span
                        class="glyphicon glyphicon-tags">&nbsp;</span>标签分类</a>
                </li>
                <li th:classappend="${n == 3} ? 'active'"><a th:href="@{/display}"><span
                        class="glyphicon glyphicon-stats">&nbsp;</span>数据一览</a>
                </li>
                <li id="bookmark" role="presentation" class='bookmark disabled'><a target="_blank"
                                                                                   th:href="@{/user/bookmark}"
                                                                                   onclick="if(localStorage.getItem('token') == null) return false;"><span
                        class="glyphicon glyphicon-bookmark">&nbsp;</span>个人书签</a>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right" id="navbar" th:fragment="navbar">
                <li class="dropdown" th:if="${user} == null">
                    <a id="a-login" class="dropdown-toggle m-padded-top" role="button" aria-haspopup="true"
                       aria-expanded="false" data-toggle="dropdown">
                        <img class="m-avatar img-circle" th:src="@{/images/user.png}">
                    </a>
                    <ul class="dropdown-menu dropdown-menu-left">
                        <li><a data-toggle="modal" data-target="#loginModal"><span
                                class="glyphicon glyphicon-log-in">&nbsp;</span>登录</a>
                        </li>
                        <li role="separator" class="divider"></li>
                        <li><a data-toggle="modal" data-target="#registerModal"><span
                                class="glyphicon glyphicon-new-window">&nbsp;</span>注册</a></li>
                    </ul>
                </li>
                <li class="dropdown" th:if="${user} != null">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">
                        <img class="m-avatar img-circle" th:src="@{${user.avatar}}">
                        <span class="caret"></span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-left">
                        <li><a th:href="@{/user/space}"><span class="glyphicon glyphicon-th">&nbsp;</span>个人主页</a>
                        </li>
                        <li role="separator" class="divider"></li>
                        <li class="bookmark"><a target="_blank" th:href="@{/user/bookmark}"><span
                                class="glyphicon glyphicon-bookmark">&nbsp;</span>个人书签</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a onclick="logout()"><span class="glyphicon glyphicon-log-out">&nbsp;</span>登出</a>
                        </li>
                    </ul>
                </li>
            </ul>

            <form class="navbar-form navbar-right" th:action="@{/search}" name="search" target="_self"
                  method="post">
                <div class="form-group">
                    <input type="text" class="form-control" th:value="${input}" name="input" placeholder="搜索"
                           style="width: 300px;">
                </div>
                <button type="submit" class="btn btn-default" onclick="document.forms['search'].submit()">
                    <a class="glyphicon glyphicon-search m-none"></a>
                </button>
            </form>

        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>

<th:block th:fragment="modal">
    <!--登录模态框-->
    <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">登录</h4>
                </div>
                <div class="modal-body">
                    <form autocomplete="on">
                        <div class="form-group">
                            <input type="text" class="form-control" name="username" id="username1"
                                   placeholder="用户名">
                        </div>
                        <div class="form-group has-feedback">
                            <input type="password" class="form-control fc-clear" name="password" id="password1"
                                   placeholder="密码">
                            <span class="m-eye">
                                <span class="eye glyphicon glyphicon-eye-open form-control-feedback m-pointer"></span>
                            </span>
                        </div>
                        <div class="form-group">
                            <input type="checkbox" name="remember" id="remember"> &nbsp;记住我
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btn-login">登录</button>
                </div>
            </div>
        </div>
    </div>

    <!--注册模态框-->
    <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="loginModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">注册</h4>
                </div>
                <div class="modal-body">
                    <form autocomplete="on">
                        <div class="form-group">
                            <input type="text" class="form-control" name="username" id="username2"
                                   placeholder="用户名">
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="email" id="email"
                                   placeholder="邮箱">
                        </div>
                        <div class="form-group form-inline">
                            <input type="text" class="form-control" name="code" id="code"
                                   placeholder="验证码">
                            <span class="input-group-btn" style="display: inline-block">
                                <button id="sendEmail" type="button" class="btn btn-success"
                                        style="width: 100px">发送验证码</button>
                            </span>
                        </div>

                        <div class="form-group has-feedback">
                            <div>
                                <input type="password" class="form-control fc-clear" name="password" id="password2"
                                       placeholder="密码">
                                <span class="m-eye">
                                    <span class="eye glyphicon glyphicon-eye-open form-control-feedback m-pointer"></span>
                                </span>
                            </div>
                        </div>
                        <div class="form-group has-feedback">
                            <div>
                                <input type="password" class="form-control fc-clear" name="repeatPassword"
                                       id="repeatPassword"
                                       placeholder="确认密码">
                                <span class="m-eye">
                                    <span class="glyphicon glyphicon-eye-open form-control-feedback"></span>
                                </span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="btn-register">注册</button>
                </div>
            </div>
        </div>
    </div>
</th:block>


<footer th:fragment="footer">
    <div>
        <div class="row">
            <div class="col-xs-12 col-sm-6 col-md-3">
                <h3>挚夕导航</h3>
                <p>
                    挚夕导航最初源于本人想要做一个管理书签的系统。
                    后来借鉴了一些导航网站，决定做一个网站导航。<br>
                </p>
            </div>
            <div class="col-xs-12 col-sm-6 col-md-9" id="footDataContainer">
                <th:block th:fragment="footData">
                    <div class="col-xs-6 col-sm-2 col-md-2" style="margin-top: 20px; margin-bottom: 20px">
                        <img class="m-footer-wechat img-thumbnail" src="../static/images/wechat.jpg"
                             th:src="@{/images/wechat.jpg}">
                    </div>
                    <div class="col-xs-6 col-sm-4 col-md-4" style="margin-top: 20px; margin-bottom: 20px">
                        <h4>联系我</h4>
                        <span>3402747477@qq.com</span>
                    </div>
                    <div class="col-xs-8 col-sm-6 col-md-3" style="margin-top: 20px; margin-bottom: 20px">
                        <h4>热门链接</h4>
                        <ul style="list-style-type: none">
                            <li th:each="link : ${footLinks}">
                                <a th:href="@{/link/{linkId}(linkId=${link.id})}" th:text="${link.title}"></a>
                            </li>
                        </ul>
                    </div>
                    <div class="col-xs-4 col-sm-6 col-md-3 " style="padding-top: 20px; margin-bottom: 20px">
                        <h4>热门标签</h4>
                        <ul style="list-style-type: none">
                            <li th:each="tag : ${footTags}">
                                <a th:href="@{/tag/{tagId}(tagId=${tag.id})}" th:text="${tag.name}"></a>
                            </li>
                        </ul>
                    </div>
                </th:block>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12" style="text-align: center; height: 50px; line-height: 50px">
                Copyright 2023-now 挚夕导航 Designed by 挚夕
            </div>
        </div>
    </div>
</footer>

<th:block th:fragment="script">
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script th:src="@{/lib/jquery-1.12.4/jquery.min.js}"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script th:src="@{/lib/bootstrap-3.4.1/js/bootstrap.min.js}"></script>
    <!--  bootstrap-dropdown-hover -->
    <script th:src="@{/lib/bootstrap-dropdown-hover.js}"></script>
    <!--  二维码生成-->
    <script th:src="@{/lib/qrcode/qrcode.min.js}"></script>
    <!-- bootstrap-bootstrapValidator-->
    <script th:src="@{/lib/bootstrapValidator/bootstrapValidator.min.js}"></script>
    <script th:src="@{/lib/bootstrapValidator/zh_CN.js}"></script>
    <!-- apache  echarts -->
    <script th:src="@{/lib/echarts-5.4.3.min.js}"></script>
    <!--  轻型信息提示框-->
    <script th:src="@{/lib/toastr/toastr.min.js}"></script>
    <!--  图片裁剪-->
    <script th:src="@{/lib/croptool.min.js}"></script>
    <script>
        function initValidator() {
            $('#loginModal').bootstrapValidator({
                excluded: [":disabled", ":hidden"], // 关键配置，表示只对于禁用域不进行验证，其他的表单元素都要验证
                message: 'This value is not valid',
                feedbackIcons: {
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    username: {
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空'
                            },
                            stringLength: {
                                min: 2,
                                max: 10,
                                message: '用户名必须在2到10位之间'
                            }
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            stringLength: {
                                min: 6,
                                max: 32,
                                message: '密码必须在6到32位之间'
                            }
                        }
                    }
                }
            });
            //表单校验
            $('#registerModal').bootstrapValidator({
                excluded: [":disabled", ":hidden"], // 关键配置，表示只对于禁用域不进行验证，其他的表单元素都要验证
                message: 'This value is not valid',
                feedbackIcons: {
                    // valid: 'glyphicon glyphicon-ok',
                    // invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    username: {
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空'
                            },
                            stringLength: {
                                min: 2,
                                max: 10,
                                message: '用户名必须在2到10位之间'
                            }
                        }
                    },
                    email: {
                        validators: {
                            notEmpty: {
                                message: '邮箱不能为空'
                            },
                            emailAddress: {
                                message: '请输入正确的邮箱'
                            }
                        }
                    },
                    code: {
                        validators: {
                            notEmpty: {
                                message: '验证码不能为空'
                            }
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            }
                        }
                    },
                    repeatPassword: {
                        validators: {
                            notEmpty: {
                                message: '密码不能为空'
                            },
                            identical: {
                                field: 'password',   //指定控件name
                                message: '两次密码不一致'
                            }
                        }
                    },
                }
            });
        }

        function clearLoginForm() {
            //登录
            $("#username1").val('');
            $("#password1").val('');
        }

        function clearRegisterForm() {
            //注册
            $("#username2").val('');
            $("#email").val('');
            $("#code").val('');
            $("#password2").val('');
            $("#repeatPassword").val('');
        }

        //登出
        function logout() {
            $.ajax({
                type: 'post',
                url: '[[@{/user/logout}]]',
                data: {
                    token: localStorage.getItem('token')
                },
                success: function (response) {
                    if (response.status == 'success') {
                        //移除本地token
                        localStorage.removeItem("token");
                        //加载导航栏
                        loadNavbar();
                        $("#bookmark").addClass('disabled');
                        window.location.href = '[[@{/}]]'
                    }
                }
            })
        }

        //加载导航栏
        function loadNavbar() {
            var token = localStorage.getItem('token');
            // console.log(token);
            $.ajax({
                type: 'get',
                url: '[[@{/user/refreshNavbar}]]',
                headers: {
                    authorization: token
                },
                success: function (data) {
                    // console.log(data)
                    $("#navbar").html(data);
                    // $('.dropdown-toggle').dropdownHover({});
                    if (token) {
                        $("#bookmark").removeClass('disabled');
                    } else {
                        $("#bookmark").addClass('disabled');
                    }
                },
                error: function (data) {
                    toastr(data, '错误')
                }
            });
        }

        //记住我
        function setCookie(key, value, day) {
            var d = new Date();
            d.setTime(d.getTime() + (day * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = key + "=" + value + "; " + expires;
        }

        function clearCookie(name) {
            document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC";
        }

        function getCookie(key) {
            const cookie = document.cookie.split(';')
            for (let i = 0, len = cookie.length; i < len; i++) {
                const cur = cookie[i].split('=')
                if (key === cur[0].trim()) {
                    return cur[1]
                }
            }
            return ''
        }

        //如果上次登录勾选记住我，本次登录加载用户名和密码
        function loadUserInfo() {
            var username = getCookie('username');
            var password = getCookie('password');
            if (username != null && username.trim() != '') {
                $("#username1").val(username);
                $("#password1").val(password);
                $("#remember").prop('checked', true);
            }
        }

        //加载数据: 最热链接/标签
        function loadHotData() {
            $.ajax({
                type: 'get',
                url: '[[@{/footer/footData}]]',
                success(data){
                    console.log(data);
                    $("#footDataContainer").html(data);
                }
            })
        }

        $(function () {
            loadHotData();
            //工具提示
            $('[data-toggle="tooltip"]').tooltip()
            //加载导航栏
            loadNavbar();
            //配置轻型信息提示框
            toastr.options = {
                "closeButton": false, //是否显示关闭按钮
                "showDuration": "300",//显示的动画时间
                "hideDuration": "1000",//消失的动画时间
                "timeOut": "2000", //展现时间
            };
            //bootstrap-dropdown-hover
            $('.navbar [data-toggle="dropdown"]').bootstrapDropdownHover({
                // see next for specifications
            });
            setTimeout(() => {
                $(".m-card").removeClass("lightSpeedIn");
            }, 2000);

            //特效
            $("body").on('mouseenter', 'li', function () {
                $(this).addClass("m-up");
            })
            $("body").on('mouseleave', 'li', function () {
                $(this).removeClass("m-up");
            })
            //登录模态框，记住我
            loadUserInfo();

            var send = false;
            var time = 60;
            var intervalId;
            //登录 注册
            initValidator();    //校验
            $('#loginModal').on('shown.bs.modal', function (event) {
                //重置表单校验
                $('#loginModal').bootstrapValidator('resetForm');
                if (getCookie('username') == null) {
                    //清空表单
                    clearLoginForm();
                }
            });
            $('#registerModal').on('shown.bs.modal', function (event) {
                //重置表单校验
                $('#registerModal').bootstrapValidator('resetForm');
                //清空表单
                clearRegisterForm();
            });
            $(".m-eye").click(function () {
                //glyphicon-eye-open glyphicon-eye-close
                //更换图标
                $(this).children('span').toggleClass("glyphicon-eye-open");
                $(this).children('span').toggleClass("glyphicon-eye-close");
                //修改input type
                if ($(this).parent().children("input").attr('type') === 'password') {
                    $(this).parent().children("input").attr('type', 'text');
                } else {
                    $(this).parent().children("input").attr('type', 'password');
                }
            });
            //发送验证码
            const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
            $("#sendEmail").click(function () {
                if (send) {
                    return;
                }
                //校验邮箱
                var email = $("#email").val();
                var res = emailPattern.test(email);
                if (!res) {
                    toastr.error("请输入正确的邮箱", '提示');
                    return;
                }
                //发送验证码
                $.ajax({
                    type: 'post',
                    url: '[[@{/user/sendMsg}]]',
                    data: {
                        email: email
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            send = true;
                            $("#sendEmail").text(time + "s");
                            intervalId = setInterval(function () {
                                time--;
                                if (time <= 0) {
                                    $("#sendEmail").text("发送验证码");
                                    send = false;
                                    time = 60;
                                } else {
                                    $("#sendEmail").text(time + "s");
                                }
                            }, 1000);
                            setTimeout(function () {
                                clearInterval(intervalId);
                            }, 60000);
                            toastr.success(response.data, '提示');
                        } else {
                            toastr.error(response.data, '提示');
                        }
                    },
                    error: function (response) {
                        toastr.error(response.data, '发送失败');
                    }
                });

            });
            //登录按钮
            $("#btn-login").click(function () {
                var bootstrapValidator = $("#loginModal").data("bootstrapValidator").validate();
                if (!bootstrapValidator.isValid()) return;
                var username = $("#username1").val();
                var password = $("#password1").val();
                var remember = $("#remember").prop('checked');
                $.ajax({
                    type: 'post',
                    url: '[[@{/user/login}]]',
                    data: {
                        username: username,
                        password: password
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            //重置表单
                            $('#loginModal').bootstrapValidator('resetForm')
                            //关闭模态框
                            $('#loginModal').modal('hide');
                            toastr.success("登录成功!", "提示")
                            //缓存token
                            localStorage.setItem("token", response.data);
                            //加载导航
                            loadNavbar();
                            window.location.href = '[[@{/}]]';
                            if (remember) {   //记住我
                                setCookie('username', username, 1);
                                setCookie('password', password, 1);
                            } else {
                                console.log('clear start')
                                clearCookie('username');
                                clearCookie('password');
                                console.log('clear end')
                            }
                        } else {
                            toastr.error(response.data.errorMessage, "提示")
                        }
                    },
                    error: function (response) {
                        toastr.error(response.data.errorMessage, "提示")
                    }
                });
            });
            //注册按钮
            $("#btn-register").click(function () {
                var bootstrapValidator = $("#registerModal").data("bootstrapValidator").validate();
                if (!bootstrapValidator.isValid()) return;
                //收集参数
                var username = $("#username2").val();
                var password = $("#password2").val();
                var email = $("#email").val();
                var code = $("#code").val();
                $.ajax({
                    type: 'post',
                    url: '[[@{/user/register}]]',
                    data: {
                        username: username,
                        password: password,
                        email: email,
                        code: code
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            //重置表单
                            $('#loginModal').bootstrapValidator('resetForm')
                            //关闭模态框
                            $('#registerModal').modal('hide');
                            toastr.success("注册成功!", "提示");
                            //缓存token
                            localStorage.setItem("token", response.data);
                            //加载导航栏
                            loadNavbar();
                        } else {
                            toastr.error(response.data.errorMessage, "提示");
                        }
                    },
                    error: function (response) {
                        toastr.error(response.data.errorMessage, "提示");
                    }
                });
            });

        });
    </script>
</th:block>

</body>

</html>